/**
 * 四川农村产权交易-“彩虹”信息平台建设采购项目
 * date: 2025-6-16
 * author: wuzhou;
 */
'use strict';

/* global */
(function (win, $) {

    // 打印功能
    document.getElementById('printBtn').addEventListener('click', function() {
        const style = document.createElement('style');
        style.textContent = `
            @page {
                size: landscape;
                margin: 0;
                zoom: 0.9;
                -ms-zoom: 0.9;
                -webkit-zoom: 0.9;
            }
            @media print {
                html {
                    zoom: 0.9 !important;
                    -ms-zoom: 0.9 !important;
                    -webkit-zoom: 0.9 !important;
                }
                html, body {
                    -webkit-print-color-adjust: exact !important;
                    print-color-adjust: exact !important;
                    height: 100% !important;
                    margin: 0 !important;
                    padding: 0 !important;
                    overflow: hidden !important;
                }
                body {
                    display: flex !important;
                    justify-content: center !important;
                    align-items: center !important;
                }
                .certificate-wrap {
                    position: relative !important;
                    margin: 0 auto !important;
                    padding: 0 !important;
                    height: 863px !important;
                    width: 1200px !important;
                    page-break-inside: avoid !important;
                    background-size: 100% 100% !important;
                    display: block !important;
                    zoom: 0.9 !important;
                    -ms-zoom: 0.9 !important;
                    -webkit-zoom: 0.9 !important;
                }
                .locate {
                    position: absolute !important;
                    backface-visibility: hidden !important;
                    -webkit-font-smoothing: antialiased !important;
                    line-height: 1 !important;
                    display: flex !important;
                    align-items: center !important;
                    justify-content: flex-start !important;
                    white-space: pre-wrap !important;
                    text-align: left !important;
                }
                .official-seal {
                    position: absolute !important;
                }
                .official-seal img {
                    max-width: 100% !important;
                    height: auto !important;
                    display: block !important;
                }
                /* 保持原有的位置信息 */
                .info1, .info2, .info3, .info4, .info5,
                .info6, .info7, .info8, .info9, .info10,
                .info11, .info12, .info13, .info14, .info15,
                .info16, .info17, .info18, .info19, .info20,
                .info21, .info22, .info23, .info24, .info25,
                .info26, .info27, .info28, .info29, .info30,
                .info31, .info32, .info33, .info34, .info35,
                .info36, .info37, .info38, .info39, .info40,
                .info41 {
                    top: var(--original-top) !important;
                    left: var(--original-left) !important;
                }
            }
        `;
        document.head.appendChild(style);

        // 保存原始位置信息
        const locateElements = document.querySelectorAll('.locate:not(.official-seal)');
        locateElements.forEach(element => {
            const computedStyle = window.getComputedStyle(element);
            element.style.setProperty('--original-top', computedStyle.top);
            element.style.setProperty('--original-left', computedStyle.left);
        });

        const originalTitle = document.title;
        document.title = '证书'; // 设置打印时的标题

        // 确保背景图片加载完成后再打印
        const bgImg = new Image();
        bgImg.src = document.querySelector('.certificate-wrap').style.backgroundImage.replace(/url\(['"]?(.*?)['"]?\)/i, '$1');
        
        // 设置打印选项
        const printOptions = {
            scale: 0.9,
            shrinkToFit: true
        };

        bgImg.onload = function() {
            // 对于Edge浏览器，尝试设置打印选项
            if (window.navigator.userAgent.indexOf('Edge') > -1) {
                window.print(printOptions);
            } else {
                window.print();
            }
            // 打印完成后恢复原始标题并移除样式
            setTimeout(() => {
                document.title = originalTitle;
                document.head.removeChild(style);
                // 清除临时样式属性
                locateElements.forEach(element => {
                    element.style.removeProperty('--original-top');
                    element.style.removeProperty('--original-left');
                });
            }, 100);
        };

        // 如果图片已经缓存，直接打印
        if (bgImg.complete) {
            if (window.navigator.userAgent.indexOf('Edge') > -1) {
                window.print(printOptions);
            } else {
                window.print();
            }
            setTimeout(() => {
                document.title = originalTitle;
                document.head.removeChild(style);
                // 清除临时样式属性
                locateElements.forEach(element => {
                    element.style.removeProperty('--original-top');
                    element.style.removeProperty('--original-left');
                });
            }, 100);
        }
    });

    // 下载为PDF功能
    document.getElementById('downloadBtn').addEventListener('click', async function() {
        const element = document.querySelector('.certificate-wrap');
        
        // 添加加载提示
        const loadingDiv = document.createElement('div');
        loadingDiv.style.position = 'fixed';
        loadingDiv.style.top = '50%';
        loadingDiv.style.left = '50%';
        loadingDiv.style.transform = 'translate(-50%, -50%)';
        loadingDiv.style.padding = '20px';
        loadingDiv.style.background = 'rgba(0,0,0,0.7)';
        loadingDiv.style.color = 'white';
        loadingDiv.style.borderRadius = '5px';
        loadingDiv.style.zIndex = '9999';
        loadingDiv.textContent = '正在生成PDF，请稍候...';
        document.body.appendChild(loadingDiv);

        try {
            const opt = {
                margin: 5,
                filename: '证书.pdf',
                image: { type: 'jpeg', quality: 1 },
                html2canvas: { 
                    scale: 2,
                    useCORS: true,
                    logging: true,
                    allowTaint: true,
                    backgroundColor: '#ffffff',
                    removeContainer: true,
                    letterRendering: true
                },
                jsPDF: { 
                    unit: 'mm',
                    format: 'a3',
                    orientation: 'landscape',
                    compress: false,
                    hotfixes: ['px_scaling']
                }
            };

            // 确保图片加载完成
            const images = element.getElementsByTagName('img');
            await Promise.all(Array.from(images).map(img => {
                if (img.complete) return Promise.resolve();
                return new Promise(resolve => {
                    img.onload = resolve;
                    img.onerror = resolve;
                });
            }));

            // 生成PDF
            await html2pdf().set(opt).from(element).save();
            
        } catch (error) {
            console.error('PDF生成错误:', error);
            alert('PDF生成失败，请重试');
        } finally {
            // 移除加载提示
            document.body.removeChild(loadingDiv);
        }
    });

})(this, jQuery);